package org.znxs.znxsojsandbox.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.znxs.znxsojsandbox.docker.DockerJavaRun;
import org.znxs.znxsojsandbox.model.ExecuteCodeRequest;
import org.znxs.znxsojsandbox.model.ExecuteCodeResponse;
import org.znxs.znxsojsandbox.model.ExecuteMessage;
import org.znxs.znxsojsandbox.model.JudgeInfo;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 具体实现
 */
@Component
@Slf4j
public abstract class CodeSandboxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "src\\main\\resources\\sandbox\\testFiles";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    @Resource
    private DockerJavaRun dockerJavaRun;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        // 非空校验
        if (executeCodeRequest == null || StrUtil.isBlank(executeCodeRequest.getCode())) {
            throw new RuntimeException("请求参数为空");
        }

        // 1. 获取代码，写入本地文件中
        File userCodeFile = saveCodeInFile(executeCodeRequest);
        // 2. 通过执行命令，进行编译，自动创建编译之后的文件
        compileFile(userCodeFile);
        // 3. 通过docker 运行程序
        List<ExecuteMessage> executeMessageList = runFile(executeCodeRequest, userCodeFile);
        // 4. 整理输出结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessageList);
        // 5. 文件清除
        boolean isClean = cleanFile(userCodeFile);
        if (isClean) {
            log.info("文件清除成功");
        }
        return executeCodeResponse;
    }


    /**
     * 获取代码，写入本地文件中
     *
     * @param executeCodeRequest 执行代码请求
     * @return
     */
    private File saveCodeInFile(ExecuteCodeRequest executeCodeRequest) {
        String userCodeParentPath = null;
        File userCodeFile = null;
        // 1) 获取代码，进行写入
        String code = executeCodeRequest.getCode();
        // 在具体的代码文件目录下面存储代码到Main文件内，并且创建不同的文件夹，
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        // 把用户的代码隔离存放
        UUID fileUUIDPath = UUID.randomUUID();
        userCodeParentPath = globalCodePathName + File.separator + fileUUIDPath;
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        userCodeFile = FileUtil.writeString(code, userCodePath, "UTF-8");
        return userCodeFile;
    }


    private void compileFile(File userCodeFile) {
        // 2) 通过执行命令，进行编译 并创建编译之后的.class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        int exitValue = 0;
        try {
            // 运行编译命令
            Process process = Runtime.getRuntime().exec(compileCmd);
            // 等待编译完成
            exitValue = process.waitFor();
        } catch (IOException | InterruptedException e) {
            // 异常处理
            log.error("编译异常", e);
            getErrorResponse(e);
        }
        log.info("编译完成，退出码为：" + exitValue + "0-正常，1-通用错误或异常情况，2-用法错误，126-命令找到但无法执行，127-命令无法找到，255-表示严重的系统错误");
    }

    private List<ExecuteMessage> runFile(ExecuteCodeRequest executeCodeRequest, File userCodeFile) {
        return dockerJavaRun.dockerRun(executeCodeRequest, userCodeFile);
    }


    private ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        // 4) 整理输出
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        ArrayList<String> outputList = new ArrayList<>();
        // 获取最大时间 判断是否超时  获取最大内存占用
        long maxTime = 0;
        long maxMemory = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            // 判断是否有错误信息
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            // 没有错误，直接添加输出用例
            outputList.add(executeMessage.getMessage());
            // 统计最长时间
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            // 统计最大内存占用
            Long memory = executeMessage.getMemory();
            if (memory != null) {
                maxMemory = Math.max(maxMemory, memory);
            }
        }

        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            // 表示运行成功
            executeCodeResponse.setStatus(1);
        }
        // 这里的message指的是整个程序执行信息
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setMemoryLimit(maxMemory);
        judgeInfo.setTime(maxTime);
        // 内存信息不容易获取，所以这里不做获取
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }


    private boolean cleanFile(File userCodeFile) {
        // 5) 文件清除
        if (userCodeFile.getParentFile() != null) {
            return FileUtil.del(userCodeFile.getParentFile().getAbsolutePath());
        }
        return false;
    }


    /**
     * 6) 错误处理
     * 异常处理方法
     *
     * @param e 程序异常
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

}
